package com.example.springmultipledatasourcesample;

import jakarta.annotation.Resource;
import jakarta.persistence.EntityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateProperties;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.util.Map;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef="entityManagerFactoryCar",
        transactionManagerRef="transactionManagerCar",
        basePackages= { "com.example.springmultipledatasourcesample.repository.car" }) //设置Repository所在位置
public class JPACarConfig {
    @Resource
    @Qualifier("carDataSource")
    private DataSource caDataSource;        //ca数据源注入
    @Resource
    private JpaProperties jpaProperties;
    @Autowired
    private HibernateProperties hibernateProperties;

    /**
     * 因为这里是住数据库，所有要加primary注解
     * @param builder
     * @return
     */
    @Primary
    @Bean(name = "entityManagerCar")        //ca实体管理器
    public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
        return entityManagerFactorycar(builder).getObject().createEntityManager();
    }

    @Primary
    @Bean(name = "entityManagerFactoryCar")    //ca实体工厂
    public LocalContainerEntityManagerFactoryBean entityManagerFactorycar (EntityManagerFactoryBuilder builder) {
        return builder
                .dataSource(caDataSource)
                .properties(getVendorProperties())
                .packages("com.example.springmultipledatasourcesample.dbcar")     //设置实体类所在位置
                .persistenceUnit("carPersistenceUnit")
                .build();
    }

    private Map<String, Object> getVendorProperties() {
        return hibernateProperties.determineHibernateProperties(
                jpaProperties.getProperties(), new HibernateSettings());
    }


    @Primary
    @Bean(name = "transactionManagerCar")         //ca事务管理器
    public PlatformTransactionManager transactionManagerPrimary(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(entityManagerFactorycar(builder).getObject());
    }
}
